<!-- eslint-disable unicorn/prefer-ternary -->
<script lang="js" setup>
import { ref, toRaw } from 'vue';

import { ElTooltip, ElTreeSelect } from 'element-plus';

import { usePlottingMapStore } from '#/store/modules/mapStore';

import lib_10 from '../../../public/symbols_json/lib_10.json';
const server = import.meta.env.VITE_GLOB_BASE_IP;
const baseUrl = import.meta.env.VITE_BASE
const mapStore = usePlottingMapStore();

const value = ref(258);
const treeDataOf10 = ref([
  {
    label: '军队标号',
    value: 10,
    selectable: false,
    children: getTreeData(lib_10.set_list, 10, 1),
  },
]);

const treeData = ref(treeDataOf10);
const activeLibID = ref(10);
const activeSetID = ref(258);
const activeSymbolList = ref(
  getNodeByID(
    getLibDataByIDInArray(toRaw(treeData.value), activeLibID.value),
    activeSetID.value,
  ).symbol_list,
);

function getLibDataByID(collectionData, activeLibId) {
  if (collectionData.value === activeLibId) {
    return collectionData;
  }

  if (collectionData.children) {
    for (const child of collectionData.children) {
      const result = getLibDataByID(child, activeLibId);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

function getLibDataByIDInArray(array, targetValue) {
  for (const item of array) {
    const result = getLibDataByID(item, targetValue);
    if (result) {
      return result; // 如果找到，返回结果
    }
  }
  return null; // 如果未找到，返回 null
}

const addSymbol = (lib_id, symbol_id) => {
  gJMP.symbolManager.activateSymbol(lib_id, symbol_id);

  document.plotting._tool_manager.switch_creating();
  mapStore.uuid = symbol_id;
  // console.log("treeData:", treeData.value);
};

function getTreeData(data, lib_id, uniqueOffset) {
  if (Array.isArray(data)) {
    return data.map((item) => getTreeData(item, lib_id, uniqueOffset)); // 递归处理数组中的每一项
  } else if (data !== null && typeof data === 'object') {
    const transformedObject = {}; // 存储转换后的对象

    for (const key in data) {
      if (Object.hasOwn(data, key)) {
        let newKey = key;

        // 将 set_name 转换为 label，将 set_id 转换为 value
        if (key === 'set_name') {
          newKey = 'label';
        }

        if (key === 'set_id') {
          transformedObject[key] = getTreeData(data[key], lib_id, uniqueOffset);
          newKey = 'value';
        }

        // 递归处理数据的属性值
        transformedObject[newKey] =
          newKey === 'value'
            ? uniqueOffset + getTreeData(data[key], lib_id, uniqueOffset)
            : getTreeData(data[key], lib_id, uniqueOffset);

        // 如果属性名为 children 且是一个数组，设置 selectable 为 false
        if (newKey === 'children' && Array.isArray(data[key])) {
          transformedObject.selectable = false;
        }

        // 处理 symbol_list 转为 children
        if (key === 'symbol_list' && Array.isArray(data[key])) {
          transformedObject.children = getTreeData(
            data[key],
            lib_id,
            uniqueOffset,
          ); // 将 symbol_list 转为 children
        }

        // 如果数据中包含 symbol_id 和 symbol_name
        if (newKey === 'symbol_id' && data.symbol_name) {
          transformedObject.value = uniqueOffset + data.symbol_id; // symbol_id -> value
          transformedObject.label = data.symbol_name; // symbol_name -> label
          transformedObject.lib_id = lib_id;
        }
      }
    }

    // 检查是否是叶子节点，添加额外的值字段以便搜索
    if (data.symbol_id && data.symbol_name && data.symbol_type !== undefined) {
      transformedObject.value = uniqueOffset + data.symbol_id; // 叶子节点的 symbol_id -> value
      transformedObject.label = data.symbol_name; // 叶子节点的 symbol_name -> label
      transformedObject.lib_id = lib_id;
    }

    return transformedObject;
  }
  return data;
}

function getNodeByID(data, id) {
  if (Array.isArray(data)) {
    for (const item of data) {
      const result = getNodeByID(item, id);
      if (result) return result;
    }
  } else if (data !== null && typeof data === 'object') {
    for (const key in data) {
      if (Object.hasOwn(data, key)) {
        if (data[key] === id) {
          return data;
        }
        const result = getNodeByID(data[key], id);
        if (result) return result;
      }
    }
  }
  return null;
}

function selectNode(_value, node) {
  // 如果 node 存在 symbol_list，赋值给 activeSymbolList
  if (node.data.symbol_list && Array.isArray(node.data.symbol_list)) {
    activeSymbolList.value = node.data.symbol_list.map((item) => {
      // 这里可以根据需求修改每个 item 的格式，例如转换为需要的 { label, value }
      return {
        label: item.symbol_name || item.label, // symbol_name 或 label
        value: item.symbol_id || item.value,
        symbol_id: item.symbol_id, // symbol_id 或 value
        lib_id: item.lib_id,
      };
    });
  } else {
    // 如果没有 symbol_list，直接处理 node
    activeSymbolList.value = [
      {
        label: node.data.symbol_name || node.label,
        value: node.data.symbol_id || node.value,
        symbol_id: node.data.symbol_id,
        lib_id: node.data.lib_id,
      },
    ];
  }
}

const filterNodeMethod = (value, data) => data.label.includes(value);
</script>

<template>
  <div class="plotting-panel">
    <ElTreeSelect
      v-model="value"
      :data="treeDataOf10"
      :render-after-expand="false"
      style="width: 100%"
      fit-input-width
      @node-click="selectNode"
      filterable
      :filter-node-method="filterNodeMethod"
    />
    <div class="func-panel symbol-lib scrollbar">
      <div
        v-for="item in activeSymbolList"
        :key="item.symbol_id"
        class="symbol-item"
        @click="addSymbol(item.lib_id, item.symbol_id)"
      >
        <ElTooltip placement="bottom" color="#3e3e3e">
          <template #content>
            <span>{{ item.label }}</span>
          </template>

          <img
            :src="`http://${server}${baseUrl}/symbols_icon/${item.lib_id}/${item.symbol_id}.png`"
          />
        </ElTooltip>
      </div>
    </div>
  </div>
</template>

<style scoped>
.plotting-panel {
  box-sizing: border-box;
  width: 100%;
  padding: 1.5vh 0.7vw;

  .func-panel {
    box-sizing: border-box;
    width: 100%;
    padding: 1vh 0.5vw;
    overflow: auto;
    user-select: none;
    background: #fff;
    border-radius: 5px;
  }

  .symbol-lib {
    height: 33vh;
    margin-top: 1.5vh;
  }

  .scene-management {
    height: 45vh;
    margin-top: 0.5vh;
  }
}

.scrollbar {
  overflow: auto;
}

.scrollbar::-webkit-scrollbar {
  width: 5px;
}

.scrollbar::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 10px;
}

.scrollbar::-webkit-scrollbar-track {
  background-color: #f1f1f1;
  border-radius: 10px;
}

.symbol-item {
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 12.5%;
  height: calc(14.5vw / 8);
  color: rgb(0 0 0);
  cursor: pointer;

  :hover {
    background: #ddd;
  }

  img {
    width: 80%;
    height: 80%;
  }
}
</style>
